package com.tarena.baking.controller;

import com.tarena.baking.common.ex.ServiceException;
import com.tarena.baking.mapper.CommentMapper;
import com.tarena.baking.mapper.ContentMapper;
import com.tarena.baking.pojo.param.CommentParam;
import com.tarena.baking.pojo.entity.Comment;
import com.tarena.baking.pojo.vo.CommentVO;
import com.tarena.baking.response.JsonResult;
import com.tarena.baking.response.StatusCode;
import com.tarena.baking.security.AuthenticationUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/comment")
public class CommentController {

    @Autowired
    CommentMapper mapper;
    @Autowired
    ContentMapper contentMapper;

    @RequestMapping("addUserComment")
    public JsonResult addUserComment(@AuthenticationPrincipal AuthenticationUser authenticationUser, @Valid @RequestBody CommentParam commentParam) {
        System.out.println("authenticationUser = " + authenticationUser + ", commentParam = " + commentParam);
        if (authenticationUser == null && commentParam.getUserId() == null) {
            System.out.println("未登录!");
            throw new ServiceException(StatusCode.ERROR_AUTHENTICATION_EMPTY,"未检测到登录信息!");
        }

        contentMapper.addCommentCount(commentParam.getContentId());
        Comment c = new Comment();
        BeanUtils.copyProperties(commentParam, c);

        c.setCreateTime(new Date());
        mapper.insert(c);
        return JsonResult.ok();
    }

    @RequestMapping("getCommentList")
    public List<CommentVO> getCommentList(Long id) {
        return mapper.getListByCommentId(id);
    }
}
